package com.photography.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photography.entity.PageResult;
import com.photography.mapper.CustomerMapper;
import com.photography.mapper.OrderMapper;
import com.photography.mapper.ProductMapper;
import com.photography.mapper.SerialMapper;
import com.photography.pojo.*;
import com.photography.service.CustomerService;
import com.photography.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.management.Query;
import java.util.*;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CustomerMapper customerMapper;

    @Autowired
    private OrderMapper orderMapper;


    @Autowired
    private SerialMapper serialMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private IdWorker idWorker;

    @Override
    public void addCustomer(CustomerVo customervo) {
        String orderId=idWorker.nextId() + "";
        String customerId=idWorker.nextId() + "";
        Customer customer = customervo.getCustomer();
        if (customer != null){
            customer.setId(customerId);
            customer.setCreated(new Date());
            customer.setUpdated(customer.getCreated());
            customerMapper.insert(customer);
        }

        List<String> serialIds = customervo.getSerialIds();
        if(!CollectionUtils.isEmpty(serialIds) && serialIds.size() > 0){
            for (String serialId : serialIds) {
                orderMapper.addSerialIdAndOrderId(serialId,orderId);
            }
        }
        List<String> productIds = customervo.getProductIds();
        if(!CollectionUtils.isEmpty(productIds) && productIds.size() > 0){
            for (String productId : productIds) {
                orderMapper.addProductIdAndOrderId(productId,orderId);
            }
        }
        Order order = customervo.getOrder();
        if (order !=null){
            order.setCustomerid(customerId);
            order.setId(orderId);
            order.setCreatetime(new Date());
            orderMapper.insert(order);
        }

    }


    @Override
    public PageResult<Customer> findAll(Customer customer,int page, int rows) {
        Page<Customer> customerPage = new Page<>(page, rows);
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq("status",1)
        .like( null != customer.getName(),"name",customer.getName())
           .apply(!StringUtils.isEmpty(customer.getStarttime()),
                "  MONTH(birthdate) >= MONTH('" + customer.getStarttime() + "')")
                .apply(!StringUtils.isEmpty(customer.getEndtime()),
                        "MONTH(birthdate) <= MONTH('" + customer.getEndtime() + "')");

        customerPage = customerMapper.selectPage(customerPage, wrapper);

        List<Customer> customerList = customerPage.getRecords();

        for (Customer c : customerList) {
            //根据客户Id获取当下所有订单
           List<Order> orderList = orderMapper.selectList(new QueryWrapper<Order>().eq(c.getId()!=null,"customerid",c.getId()));
           if(!CollectionUtils.isEmpty(orderList)){
               for (Order order : orderList) {


                       List<Serial> serials = serialMapper.findSerialByOrderId(order.getId());
                       if (!CollectionUtils.isEmpty(serials)){
                           order.setSerials(serials);
                       }

                       List<String> productids = productMapper.findProductidsByOrderId(order.getId());

                       if (!CollectionUtils.isEmpty(productids)){
                           ArrayList<Product> list = new ArrayList<>();
                           for (String productid : productids) {
                               Product product = productMapper.selectById(productid);
                               list.add(product);
                           }
                           order.setProducts(list);
                       }

               }
               //设置用户所有订单
               c.setOrders(orderList);
           }

        }

        PageResult<Customer> customerPageResult = new PageResult<>(customerPage.getTotal(),customerPage.getRecords());
        return customerPageResult;
    }

    @Override
    public void updateCustomer(Customer customer) {
        customerMapper.updateById(customer);
    }


    @Override
    public void update(Customer customer) {
        customerMapper.updateById(customer);
    }

    @Override
    public void deleteCustomerByIds(String[] ids) {
        for (String id : ids){
            Customer customer = customerMapper.selectById(id);
            customer.setStatus(0);
            customerMapper.updateById(customer);
        }
    }

    @Override
    public void deleteCustomer(Customer customer) {
        customerMapper.deleteById(customer);
        List<Order> orders = customer.getOrders();
        if (!CollectionUtils.isEmpty(orders)){
            for (Order order : orders) {
                orderMapper.deleteById(order);

                if (!CollectionUtils.isEmpty(order.getSerials())){
                    for (Serial serial : order.getSerials()) {
                        serialMapper.deleteById(serial);
                    }
                }

                if (!CollectionUtils.isEmpty(order.getProducts())){
                    for (Product product : order.getProducts()) {
                        serialMapper.deleteById(product);
                    }
                }
            }
        }



    }

    @Override
    public Customer findOne(String phonenumber) {
//        Customer customer = new Customer();
//        customer.setPhonenumber(phonenumber);
        return customerMapper.selectOne(new QueryWrapper<Customer>().eq(phonenumber!=null,"phonenumber",phonenumber));
    }
}
